package org.example.trans.controller;

import org.example.trans.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jdbc.datasource.DataSourceTransactionManager;
import org.springframework.transaction.TransactionDefinition;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.DefaultTransactionDefinition;
import org.springframework.util.Assert;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RequestMapping("/user")
@RestController
public class userController {
    @Autowired
    private UserService userService;
    @Autowired
    private DataSourceTransactionManager transactionManager;
    @Autowired
    TransactionDefinition transactionDefinition = new DefaultTransactionDefinition();

    @RequestMapping("/register")
    public String register(String name, String password) {
//        开启事务
        TransactionStatus transaction = transactionManager.getTransaction(transactionDefinition);

//        判断username与password不能为空
        Assert.notNull(name, "username must not be null");
        Assert.notNull(password, "password must not be null");
        userService.insert(name,password);
//        回滚事务
//        transactionManager.rollback(transaction);
//        提交事务
        transactionManager.commit(transaction);
        transactionManager.rollback(transaction);
        return "success";
    }
}
